import axios from 'axios'
import { useRouter } from 'vue-router'

// 服务名与baseURL映射
const SERVICE_BASE_URLS = {
  rbac: 'http://10.222.11.13:8073',  //Write
  auth: 'http://10.222.11.13:8063'  //Read
}

// 创建axios实例
const service = axios.create({
  baseURL:'',
  timeout: 10000 // 超时时间，可根据需要调整
})

// 请求拦截器，自动携带Token
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('Token') || localStorage.getItem('token')
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器，处理401错误
service.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('Token')
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 如果不是在登录页面，则跳转到登录页
      if (window.location.pathname !== '/') {
        window.location.href = '/'
      }
    }
    return Promise.reject(error)
  }
)

// 通用请求方法，支持serviceName
export function apiRequest(options: {
  url: string,
  method?: 'get' | 'post' | 'put' | 'delete',
  data?: any,
  params?: any,
  baseURL?: string,
  serviceName?: keyof typeof SERVICE_BASE_URLS
}) {
  const baseURL = options.baseURL || (options.serviceName ? SERVICE_BASE_URLS[options.serviceName] : undefined)
  return service({
    url: options.url,
    method: options.method || 'get',
    data: options.data,
    params: options.params,
    baseURL
  })
}

export default service 